import type { InjectionKey } from 'vue'

const APPLY_PREVIEW_KEY: InjectionKey<Ref<boolean>> = Symbol.for('APPLY_PREVIEW_KEY')

export function providerApplyPreview(val: Ref<boolean>) {
  provide(APPLY_PREVIEW_KEY, val)
}

export function injectApplyPreview() {
  return inject(APPLY_PREVIEW_KEY)
}

export function useCountDown(c = 10) {
  let timer = 0

  const count = ref(0)

  const isZero = computed(() => {
    return count.value === 0
  })

  onUnmounted(() => {
    clearInterval(timer)
  })

  function start() {
    count.value = c
    clearInterval(timer)
    timer = window.setInterval(() => {
      count.value -= 1

      if (count.value < 1)
        clearInterval(timer)
    }, 1000)
  }

  function stop() {
    clearInterval(timer)
    count.value = 0
  }

  return { isZero, count, start, stop }
}
